package com.seari.AlarmSystem.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * 配置文件工具类
 */
public final class PropertiesUtil {

    /**
     * 配置文件工具类
     * @param url
     * @param propName
     * @param defaultValue
     * @return
     */
    public static final String loadProperties(String url, String propName, String defaultValue) {
        Properties prop = new Properties();
        try {
			prop.load(new FileInputStream(url));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        String returnValue = prop.getProperty(propName, defaultValue);
        return returnValue;
    }

    /**
     * 返回classpath下指定文件名，指定key的值
     * @param fileName
     * @param key
     * @return
     */
    public static final String getProperty(String fileName, String key) {
        Properties prop = new Properties();
        InputStreamReader in = null;
		try {
			in = new InputStreamReader(PropertiesUtil.class.getResourceAsStream("/" + fileName),"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
        if(in != null){
            try {
                prop.load(in);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        String value = new String(prop.getProperty(key));
			
        return value;
    }

    /**
     * 返回classpath下指定文件名的Properties对象
     * @param fileName
     * @return
     */
    public static final Properties getProperties(String fileName) {
        Properties prop = new Properties();
        InputStream in = PropertiesUtil.class.getResourceAsStream("/" + fileName);
        try {
            prop.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prop;
    }

    /**
     * 获取指定properties对象，指定key的值
     * @param prop
     * @param key
     * @return
     */
    public static final String getValue(Properties prop,String key){
    	String value = "";
    	try{
            value = prop.getProperty(key);
    	}catch(Exception e){
    		 e.printStackTrace();
    	}
    	
    	return value;
    }
    
    
    public static void main(String[] args) {
    	
    	PropertiesUtil pu = new PropertiesUtil();
    	String keyAi = pu.getProperty("commonConfig.properties","keyAi");
    	System.out.println("===PropertiesUtil.keyAi==="+keyAi);
	}
}
